package com.twang.stock.task;

import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.JsonPath;
import com.twang.stock.Entity.ShiShiData;
import com.twang.stock.common.DateUtil;
import com.twang.stock.common.http.HtmlTools;
import com.twang.stock.entity.DfcfBnakKuai;
import com.twang.stock.entity.DfcfHuGangTong;
import com.twang.stock.entity.DfcfZhangDie;
import com.twang.stock.entity.TodayQinXu;
import com.twang.stock.mapper.TodayQinXuMapper;
import com.twang.stock.task.old.BaseTask;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.Header;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.List;

/**
 * @param ：
 * 每日14：57更新
 * 即时--http://data.10jqka.com.cn/funds/gnzjl/ajax/1/free/1/
 *             3日：http://data.10jqka.com.cn/funds/gnzjl/board/3/ajax/1/free/1/
 *             5日：http://data.10jqka.com.cn/funds/gnzjl/board/5/ajax/1/free/1/
 *           明细：http://q.10jqka.com.cn/gn/detail/code/300845/
 */
@Slf4j
@Component
public class QueryZhangDieTingTask extends BaseTask {

    public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36";
    public static String COOKIE = "v=A3mH6ooqPRK0e-GGeAjFux6xiO5Qhm04V3qRzJuu9aAfIpcY49Z9COfKoZ0o";

    public static String URL = "http://q.10jqka.com.cn/api.php?t=indexflash&";

    public static String AMOUNT_CACTH_KEY="QUERYZHANGDIETINGTASK_TOTAL_AMOUNT";

    @Resource
    private TodayQinXuMapper todayQinXuMapper;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;


    @Scheduled(cron = "0 0/1 * * * ?")
    public void excute() {
      try {
          if (!isWorkTradeTime()) {
              return;
          }

          asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
              try {
                  getZDT();
              } catch (Exception e) {
                  log.info("error = {}", e);
              }
              log.info("==========> 查询大盘板块数据  QueryBanKuaiAndDaPan end!");
          });

      } catch (Exception e) {
          throw e;
      }
  }
    public TodayQinXu query(TodayQinXu param){
        return todayQinXuMapper.select(param).get(0);
    }

    public TodayQinXu getZDT() {

        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        TodayQinXu todayQinXu = new TodayQinXu();
        todayQinXu.setDate(DateUtil.getToday().substring(0, 8));
        try {
            String htmlForStock = getHtmlStrByUrl(URL, httpClient, COOKIE, USER_AGENT);
            // 网页内容解析
            log.info("该网页存在,正在解析:{}", htmlForStock);
            //获取分时涨停数
            todayQinXu.setNowZtzs(new BigDecimal(JsonPath.read(htmlForStock, "$.zdt_data.last_zdt.ztzs").toString()));
            //获取分时跌停数
            todayQinXu.setNowDtzs(new BigDecimal(JsonPath.read(htmlForStock, "$.zdt_data.last_zdt.dtzs").toString()));
            //获取分时涨停数集合【9：30-11：30，13：00-15：00】
            List<String> times = JsonPath.read(htmlForStock, "$.zdt_data.zd_time");
            todayQinXu.setMinutes(times.get(times.size() - 1).replace(":", ""));
            //全A涨跌分布（上涨）
            JsonPath.read(htmlForStock, "$.zdfb_data.znum");
            todayQinXu.setZtzs(new BigDecimal(JsonPath.read(htmlForStock, "$.zdfb_data.znum").toString()));
            //全A涨跌分布（下跌）
            JsonPath.read(htmlForStock, "$.zdt_data.dtzs");
            todayQinXu.setDtzs(new BigDecimal(JsonPath.read(htmlForStock, "$.zdfb_data.dnum").toString()));
            //沪市成交量
            ShiShiData shiShiData = HtmlTools.getGpdatas(Lists.newArrayList("sh000001")).get(0);
            // 发送请求，并执行
           // StockFromTHSDto stockFromTHSDto= ExcuteWarningTask.getData("1A0001");
            todayQinXu.setShTradeVol(new BigDecimal(shiShiData.getSumvol()));
            //沪市成交额
            todayQinXu.setShTradeSum(new BigDecimal(shiShiData.getAmount()));
            //深市成交量
             shiShiData = HtmlTools.getGpdatas(Lists.newArrayList("sz399001")).get(0);
            todayQinXu.setSzTradeVol(new BigDecimal(shiShiData.getSumvol()));
            //深市成交量
            todayQinXu.setSzTradeSum(new BigDecimal(shiShiData.getAmount()));
            //总成交额
            todayQinXu.setTotalAmount(todayQinXu.getShTradeSum().add(todayQinXu.getSzTradeSum()));

            try {
                TodayQinXu temp = new TodayQinXu();
                temp.setDate(todayQinXu.getDate());
                temp.setMinutes(todayQinXu.getMinutes());
                if (CollectionUtils.isNotEmpty(todayQinXuMapper.select(temp))) {
                    todayQinXuMapper.delete(temp);
                }
                todayQinXuMapper.insert(todayQinXu);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } catch (Exception e) {
            log.error("erro={}", e);
        }
        return todayQinXu;
    }


//    private void initTag(String stockName,GaiNianZiJingPaiHang info, List<StockInfo> stockInfoList,BigDecimal zhangDie){
//        try {
//            CompanyCodeInfo companyCodeInfo= companyCodeInfoService.getInfoByStockName(stockName);
//            if(null==companyCodeInfo){
//                return;
//            }
//            StockInfo stockInfo=new StockInfo();
//            stockInfo.setCode(companyCodeInfo.getCompanyCode());
//            stockInfo.setZhangdie(null==zhangDie?BigDecimal.ZERO:zhangDie);
//            stockInfoList.add(stockInfo);
//            hotTagService.inserStockTag(hot_tag_id.longValue(),companyCodeInfo.getId(),info);
//        }catch (Exception e){
//            log.error("生成Tag 失败 error={}",e);
//        }
//    }


    public static String getHtmlStrByUrl(String url, CloseableHttpClient httpClient, String COOKIE, String USER_AGENT) throws Exception {
        HttpGet httpGetForFName = new HttpGet(url);
        httpGetForFName.addHeader("User-Agent", USER_AGENT);
        httpGetForFName.addHeader("Cookie", getCOOKIE());
        httpGetForFName.addHeader("Content-Type", "text/html; charset=gbk");
        httpGetForFName.addHeader("Accept-Encoding", "gzip, deflate");
        httpGetForFName.addHeader("Connection", "keep-alive");
        // 发送请求，并执行
        CloseableHttpResponse response;
        String html = "";
        try {
            response = httpClient.execute(httpGetForFName);
            // response植入cookie
            Header[] ssoResponseHeader = response.getHeaders("Set-Cookie");
            InputStream in = response.getEntity().getContent();
            html = convertStreamToString(in);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return html;
    }

    public static String convertStreamToString(InputStream in) {
        StringBuilder sb = new StringBuilder();
        try {

            InputStreamReader isr = new InputStreamReader(in, "gbk");
            BufferedReader reader = new BufferedReader(isr);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();

    }

    private static String getCOOKIE() throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        // String jsFileName = GaiNianZiJingPaiHangTask.class.getClassLoader().getResource("static/js/aes.min.js").getFile(); // 读取js文件
        // FileReader reader = new FileReader(); // 执行指定脚本
        //spring boot 不能直接这样读取路径，jar包中会报错
        ClassPathResource classPathResource = new ClassPathResource("static/js/aes.min.js");
        InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream());
        engine.eval(reader);
        if (engine instanceof Invocable) {
            Invocable invoke = (Invocable) engine; // 调用merge方法，并传入两个参数
            // c = merge(2, 3);
            String c = (String) invoke.invokeFunction("v");
            COOKIE = "v=" + c;
        }
        reader.close();
        return COOKIE;
    }

    public static void main(String[] args) throws Exception {

        HtmlTools.getGpdatas(Lists.newArrayList("sz399001")).get(0);
    }
}
